import os
import shutil
import argparse

import App_setting as setting
from WebBackend.store.functions.configuration_functions import get_configuration_file_path, clean_comment
from WebBackend.utils.encryption.myssl import generate_certificate


def __create_folder__():
    keys = vars(setting.path)
    for key in keys.keys():
        if str(key).startswith('dir'):
            t = str(eval('setting.path.' + str(key)))
            if not os.path.exists(t):
                try:
                    os.mkdir(t)
                    print("created folder:", t)
                except FileNotFoundError as e:
                    print("Could not create folder:", t)
        elif str(key).startswith('file'):
            if str(key).endswith('log'):
                t = str(eval('setting.path.' + str(key)))
                if not os.path.exists(t):
                    try:
                        with open(t, 'w') as f:
                            f.close()
                        print("created file:", t)
                    except any as e:
                        print("Could not create file:", t)
        else:
            pass



def __create_ssl__():
    if not os.path.exists(setting.path.file_ssl_key) \
            or not os.path.exists(setting.path.file_ssl_cert) \
            or not os.path.exists(setting.path.dir_web_backend_folder):
        generate_certificate(certfilename=setting.path.file_ssl_cert, keyfilename=setting.path.file_ssl_key)


def __create_backup__():
    true_configuration_file: str = get_configuration_file_path()
    if os.path.exists(true_configuration_file):
        if not os.path.exists(setting.path.file_vsftpd_conf_local_backup):
            print('creating vsftpd.conf local backup')
            shutil.copy(true_configuration_file, setting.path.file_vsftpd_conf_local_backup)
        if not os.path.exists(setting.path.file_vsftpd_conf_prog_backup):
            print('creating vsftpd.conf program backup')
            shutil.copy(true_configuration_file, setting.path.file_vsftpd_conf_prog_backup)
        clean_comment(setting.path.file_vsftpd_conf)
    else:
        print(f'file preflight failed: {setting.path.file_vsftpd_conf} config file not found')

    if os.path.exists(setting.path.file_samba_conf):
        if not os.path.exists(setting.path.file_samba_conf_local_backup):
            print('creating smb.conf local backup')
            shutil.copy(setting.path.file_samba_conf, setting.path.file_samba_conf_local_backup)
        if not os.path.exists(setting.path.file_samba_conf_prog_backup):
            print('creating smb.conf program backup')
            shutil.copy(setting.path.file_samba_conf, setting.path.file_samba_conf_prog_backup)
        clean_comment(setting.path.file_samba_conf)
    else:
        print(f'file preflight failed: {setting.path.file_samba_conf} config file not found')
    return true_configuration_file


def __generate_service__(service_name: str = 'sea-archiver'):
    working_dir = os.getcwd()
    text = f"""#[link] /usr/lib/systemd/system/{service_name}.service 
[Unit]
Description="App_SeaArchiver.py A vsftpd/samba manager web ui"
After=network.target

[Service]
#User=
#Group=
WorkingDirectory={working_dir}/
#Environment="PATH=/usr/bin/python3:/home/username/venv/bin"
ExecStart={working_dir}/venv/bin/python3 {working_dir}/App_SeaArchiver.py
Restart=always
StandardOutput=journal+file:/var/log/{service_name}.log
StandardError=journal+file:/var/log/{service_name}.log

[Install]
WantedBy=multi-user.target
"""
    with open(os.path.join(working_dir, 'service', f'{service_name}.service'), 'w') as f:
        f.write(text)
        f.close()


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--service_name', required=False, help='custom your service name')
    args = parser.parse_args()
    ########################################
    __create_folder__()
    __create_ssl__()
    __create_backup__()
    __generate_service__(args.service_name or 'sea-archiver')
